﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;
using Db4objects.Db4o.Linq;

namespace DataLayer.Model
{
    public class Transferencia
    {
        public Conta ContaOrigem { get; set; }
        public Conta ContaDestino { get; set; }
        public decimal Valor { get; set; }
        public Guid ID { get; set; }
        public void Salvar()
        {
            this.ID = Guid.NewGuid();
            IObjectContainer client = DataLayer.Core.Server.OpenClient();

            this.ContaOrigem = (from Conta p in client
                                where p.ID == this.ContaOrigem.ID
                                select p).Single();

            this.ContaDestino = (from Conta p in client
                                 where p.ID == this.ContaDestino.ID
                                 select p).Single();


            Model.System system = (from Model.System s in client
                                   select s).Single();

            /*INICIO DA TRANSFERENCIA*/
            Lancamento lout = new Lancamento();
            lout.Descricao = "TRANSFERÊNCIA " + this.ContaOrigem.Descricao + " >> " + this.ContaDestino.Descricao;
            lout.Valor = this.Valor * -1;
            lout.ID = Guid.NewGuid();
            lout.Conta = this.ContaOrigem;
            lout.DataPagamento = DateTime.Now;
            lout.DataVencimento = DateTime.Now;
            lout.Categoria = (from Categoria p in client
                              where p.ID == system.IDTransferenciaOut
                              select p).Single();


            Lancamento lin = new Lancamento();
            lin.Descricao = "TRANSFERÊNCIA " + this.ContaOrigem.Descricao + " >> " + this.ContaDestino.Descricao;
            lin.Valor = this.Valor;
            lin.ID = Guid.NewGuid();
            lin.Conta = this.ContaDestino;
            lin.DataPagamento = DateTime.Now;
            lin.DataVencimento = DateTime.Now;
            lin.Categoria = (from Categoria p in client
                             where p.ID == system.IDTransferenciaIN
                             select p).Single();

            client.Store(lout);
            client.Store(lin);
            client.Store(this);

            try
            {
                client.Commit();
            }
            catch (Exception)
            {
                client.Rollback();
            }

            DataLayer.Core.Server.CloseClient(client);
        }
    }
}
